package multi_thread.train;

import java.util.*;
import java.util.concurrent.*;

/**
 * @author Cheng Jun
 * Description: 请输入描述
 * @version 1.0
 * @date 2022/9/16 9:21
 */
public class VerifyThreadPool {

    public static void main(String[] args) throws InterruptedException {
        int times = 100_000;
        // noThread time 13
        // noThread(times);

        // noConcurrentLoop time 16457
        // noConcurrentLoop(times);

        // concurrentLoop time 16922
        // concurrentLoop(times);

        // threadPool 362
        threadPool(times);
    }

    private static void noThread(int times) {
        Queue<Integer> queue = new LinkedList<Integer>();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            int randomNum = ThreadLocalRandom.current().nextInt();
            queue.add(randomNum);
        }
        System.out.println("noThread time " + (System.currentTimeMillis() - startTime));
    }

    private static void noConcurrentLoop(int times) throws InterruptedException {
        ConcurrentLinkedQueue<Integer> numQueue = new ConcurrentLinkedQueue<>();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            Thread thread = new Thread(() -> {
                int randomNum = ThreadLocalRandom.current().nextInt();
                numQueue.add(randomNum);
            });
            thread.start();
            thread.join();
        }
        System.out.println("noConcurrentLoop time " + (System.currentTimeMillis() - startTime));
    }

    private static void concurrentLoop(int times) throws InterruptedException {
        ConcurrentLinkedQueue<Integer> numQueue = new ConcurrentLinkedQueue<>();
        Thread thread = null;
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            thread = new Thread(() -> {
                int randomNum = ThreadLocalRandom.current().nextInt();
                numQueue.add(randomNum);
            });
            thread.start();
        }
        thread.join();
        System.out.println("concurrentLoop time " + (System.currentTimeMillis() - startTime));
    }

    private static void threadPool(int times) throws InterruptedException {
        ConcurrentLinkedQueue<Integer> numQueue = new ConcurrentLinkedQueue<>();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++) {
            Thread thread = new Thread(() -> {
                int randomNum = ThreadLocalRandom.current().nextInt();
                numQueue.add(randomNum);
            });
            executorService.execute(thread);
        }
        executorService.shutdown();
        executorService.awaitTermination(1, TimeUnit.HOURS);
        System.out.println("threadPool " + (System.currentTimeMillis() - startTime));
    }
}
